package com.roncoo.education.course.service.admin.biz;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Component;

import com.roncoo.education.common.core.base.Page;
import com.roncoo.education.common.core.base.PageUtil;
import com.roncoo.education.common.core.base.Result;
import com.roncoo.education.common.core.enums.StatusIdEnum;
import com.roncoo.education.common.core.tools.BeanUtil;
import com.roncoo.education.common.core.tools.DateUtil;
import com.roncoo.education.common.elasticsearch.EsPost;
import com.roncoo.education.common.service.BaseBiz;
import com.roncoo.education.course.dao.PostDao;
import com.roncoo.education.course.dao.impl.mapper.entity.Post;
import com.roncoo.education.course.dao.impl.mapper.entity.PostExample;
import com.roncoo.education.course.dao.impl.mapper.entity.PostExample.Criteria;
import com.roncoo.education.course.service.admin.req.AdminPostEditReq;
import com.roncoo.education.course.service.admin.req.AdminPostPageReq;
import com.roncoo.education.course.service.admin.req.AdminPostSaveReq;
import com.roncoo.education.course.service.admin.resp.AdminPostPageResp;
import com.roncoo.education.course.service.admin.resp.AdminPostViewResp;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;

/**
 * ADMIN-实验信息
 *
 * @author wujing
 */
@Component
@RequiredArgsConstructor
public class AdminPostBiz extends BaseBiz {

    @NotNull
    private final PostDao dao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 实验信息分页
     *
     * @param req 实验信息分页查询参数
     * @return 实验信息分页查询结果
     */
    public Result<Page<AdminPostPageResp>> page(AdminPostPageReq req, Long userId) {
        PostExample example = new PostExample();
        Criteria c = example.createCriteria();
        example.setOrderByClause("gmt_create desc");
        Page<Post> page = dao.page(req.getPageCurrent(), req.getPageSize(), example);
        Page<AdminPostPageResp> respPage = PageUtil.transform(page, AdminPostPageResp.class);
        return Result.success(respPage);
    }

    /**
     * 实验信息添加
     *
     * @param req 实验信息
     * @return 添加结果
     */
    public Result<String> save(AdminPostSaveReq req, Long userId) {
        Post record = BeanUtil.copyProperties(req, Post.class);
        record.setUserId(userId);
        if (dao.save(record) > 0) {
            EsPost esPost = BeanUtil.copyProperties(record, EsPost.class);
            elasticsearchRestTemplate.index(new IndexQueryBuilder().withObject(esPost).build(), IndexCoordinates.of(EsPost.POST));        	        	
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     * 实验信息查看
     *
     * @param id 主键ID
     * @return 实验信息
     */
    public Result<AdminPostViewResp> view(Long id) {
        return Result.success(BeanUtil.copyProperties(dao.getById(id), AdminPostViewResp.class));
    }

    /**
     * 实验信息修改
     *
     * @param req 实验信息修改对象
     * @return 修改结果
     */
    public Result<String> edit(AdminPostEditReq req) {
        Post record = BeanUtil.copyProperties(req, Post.class);
        if (dao.updateById(record) > 0) {
        	EsPost esPost = BeanUtil.copyProperties(record, EsPost.class);
            elasticsearchRestTemplate.index(new IndexQueryBuilder().withObject(esPost).build(), IndexCoordinates.of(EsPost.POST));
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     * 实验信息删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        if (dao.deleteById(id) > 0) {
        	elasticsearchRestTemplate.delete(id.toString(), EsPost.class);
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }
    
    public void syncEs() {
        // 获取全部全景
        PostExample example = new PostExample();
        example.createCriteria().andStatusIdEqualTo(StatusIdEnum.YES.getCode());
        List<Post> postList = dao.listByExample(example);
        if (CollUtil.isNotEmpty(postList)) {
            List<IndexQuery> queries = new ArrayList<>();
            for (Post post : postList) {
                EsPost esPost = BeanUtil.copyProperties(post, EsPost.class);
                esPost.setGmtCreate(DateUtil.fromLocalDateTime(post.getGmtCreate()));
                esPost.setGmtModified(DateUtil.fromLocalDateTime(post.getGmtModified()));

				queries.add(new IndexQueryBuilder().withObject(esPost).build());
            }
            // 更新es
            elasticsearchRestTemplate.indexOps(EsPost.class).delete();
            elasticsearchRestTemplate.bulkIndex(queries, IndexCoordinates.of(EsPost.POST));
        }      
    }     
}
